/**
 * 系统管理 用户管理
 */
<template>
  <div>
    <!-- 面包屑导航 type-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="searchForm" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="searchForm.no" placeholder="请输入工号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-search" @click="searchPlus">高级搜索</el-button>
        <el-button size="small" type="success" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button size="small" type="danger" @click="batchDelete">批量删除</el-button>
        <el-button size="small"  @click="resetPage()">展示所有用户</el-button>
      </el-form-item>
    </el-form>

    <!--用户列表-->
    <el-table size="small" @selection-change="handleSelectionChange" :data="userData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;" :row-key="getRowKeys" ref="multipleSelectable">
      <el-table-column align="center" type="selection" width="50"></el-table-column>
      <el-table-column align="center" sortable prop="id" label="序号" width="80"></el-table-column>
      <el-table-column align="center" sortable prop="no" label="工号" width="100"></el-table-column>
      <el-table-column align="center" sortable prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column align="center" sortable prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column align="center" sortable prop="telphone" label="手机" min-width="120"></el-table-column>
      <el-table-column align="center" sortable prop="email" label="邮箱" min-width="160"></el-table-column>
      <el-table-column align="center" sortable prop="account" label="系统账户" min-width="120"></el-table-column>
      <el-table-column align="center" sortable prop="organization" label="所属组织" min-width="120"></el-table-column>
      <el-table-column align="center" sortable prop="director" label="负责人" min-width="120"></el-table-column>
      <el-table-column align="center" sortable prop="position" label="任职岗位" min-width="120"></el-table-column>
      <el-table-column align="center" sortable prop="role_id" label="角色id" min-width="120"></el-table-column>
      <el-table-column align="center" sortable prop="roles" label="角色" min-width="120"></el-table-column>
      <el-table-column sortable prop="status" label="用户状态" width="180" align="center">
          <template slot-scope="scope">
            <div><StatusSwitch :mystatus="scope.row.status" :mydisabled="true" @changeSwitch="changeSwitch"></StatusSwitch></div>
          </template>
      </el-table-column>
      <el-table-column label="操作" min-width="300" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
          <el-button size="mini" type="warning" @click="rolesChanges(scope.$index, scope.row)">角色配置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <!-- 编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="40%" @click='closeDialog("edit")' >
      <el-form label-width="80px" ref="editForm" :model="editForm" :rules="rules" inline>
        <el-form-item label="工号" prop="no">
          <el-input v-model="editForm.no" auto-complete="off" placeholder="请输入工号" :disabled="isdisabled" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" auto-complete="off" placeholder="请输入姓名" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" auto-complete="off" placeholder="请输入用户名" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="telphone">
          <el-input v-model="editForm.telphone" placeholder="请输入手机号" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱地址" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="系统账户" prop="account">
          <el-input v-model="editForm.account" placeholder="请输入系统账户" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="所属组织" prop="organization">
          <el-input v-model="editForm.organization" auto-complete="off" placeholder="请选择所属组织" @focus="showOrganization" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="director">
          <el-input v-model="editForm.director" placeholder="请选择负责人" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="任职岗位" prop="position">
          <el-select v-model="editForm.position" placeholder="请选择岗位" style="width: 220px">
            <el-option v-for="item in positionData" :label="item.name" :value="item.name" :key="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="角色id" prop="role_id">
          <el-input v-model="editForm.role_id" placeholder="请输入角色id" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item sortable prop="status" label="启用状态">
          <div><StatusSwitch :mystatus="editForm.status" :mydisabled="false" @changeSwitch="changeSwitch"></StatusSwitch></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click='closeDialog("edit")'>取消</el-button>
        <el-button type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
    <!-- 组织选择界面 -->
    <el-dialog title="选择所属组织" :visible.sync="organizationFormVisible" width="50%" @click="closeDialog">
      <el-table ref="singleTable" :data="organizationData" highlight-current-row @current-change="handleCurrentChange" style="width: 100%">
          <el-table-column prop="org_no" label="组织编码"  width="220"></el-table-column>
          <el-table-column prop="org_name" label="组织名称" width="220"></el-table-column>
          <el-table-column prop="org_type" label="组织类型" width="220"></el-table-column>
          <el-table-column prop="director" label="负责人" width="220"></el-table-column>
      </el-table>
      <el-pagination
      @size-change="pageSizeChange"
      @current-change="pageCurrentChange"
      :current-page="orgPageData.currentPage"
      :page-sizes="[10, 15, 20]"
      :page-size="orgPageData.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="orgPageData.total">
      </el-pagination>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeOrganization">取消</el-button>
          <el-button size="small" type="primary" class="title" @click="submitOrganization()">保存</el-button>
        </div>
    </el-dialog>
    <!-- 高级搜索 -->
    <el-dialog title="高级搜索" :visible.sync="searchVisible" width="38%" @click="closeDialog">
      <el-form ref="searchForm" :model="searchForm" label-width="80px" inline>
        <el-form-item label="工号">
          <el-input v-model="searchForm.no" placeholder="请输入用户工号" style="width:220px"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" auto-complete="off" placeholder="请输入姓名" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" style="width:220px"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input v-model="searchForm.email" placeholder="请输入邮箱地址" style="width: 220px"></el-input>
        </el-form-item>
        <el-form-item label="所属组织">
          <el-select v-model="searchForm.organization" placeholder="请选择组织" style="width:220px">
            <el-option v-for="item in orgs" :label="item.org_name" :value="item.org_name" :key="item.org_name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="任职岗位">
          <el-select v-model="searchForm.position" placeholder="请选择岗位" style="width:220px">
            <el-option v-for="item in positionData" :label="item.name" :value="item.name" :key="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item sortable prop="status" label="启用状态">
          <div><StatusSwitch :mystatus="searchForm.status" :mydisabled="false" @changeSwitch="changeSwitch_search"></StatusSwitch></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="resetCondition">重置</el-button>
        <el-button @click='closeDialog("高级搜索")'>取消</el-button>
      </div>
    </el-dialog>

    <!-- 角色配置 -->
    <el-dialog title="角色配置" :visible.sync="rolesVisible" width="38%" @click="closeDialog">
      <el-tree
        :data="rolesData"
        show-checkbox
        node-key="id"
        ref="tree"
        :default-expand-all="isExpand"
        :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveRoles()">保存</el-button>
        <el-button @click='closeDialog("角色配置")'>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入请求方法
import Pagination from '../../components/Pagination'
import StatusSwitch from "../../components/orgComponet/StatusSwitch.vue";
export default {
  data() {
    var checkNo = (rule, value, callback) => {
      if(this.title == '添加用户'){
        console.log('1校验器title',this.title);
        this.$axios.get("/api/user/no/"+value).then(Response => {
          if(Response.data.code==500) {
            callback();
          }
          callback(new Error('工号已存在！'));
        })
      }else{
        console.log('2校验器title',this.title);
        callback();
      }
    };
    var checkUsername = (rule, value, callback) => {
      if(this.title == '添加用户'){
        console.log('1校验器title',this.title);
        this.$axios.get("/api/user/username/"+value).then(Response => {
          if(Response.data.code==500) {
            callback();
          }
          callback(new Error('用户名已存在！'));
        })
      }else{
        console.log('2校验器title',this.title);
        callback();
      }
    };
    return {
      positionData:[],//岗位数据
      organizationTypeData:[],//组织类别数据
      dialogTableVisible: false,
      loading: false, //是显示加载
      multipleSelection: [],//勾选组织ids
      title: '添加用户',
      editFormVisible: false, //控制编辑页面显示与隐藏
      unitAccessshow: false, //控制所属单位隐藏与显示
      organizationFormVisible: false,//控制所属组织的显示与隐藏
      searchVisible:false,//控制高级搜索框的显示与隐藏
      rolesVisible:false,//控制角色配置框的显示与隐藏
      isExpand:true,//控制树状图默认展开
      userid:'',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rolesData:[],
      // 编辑与添加
      editForm: {
        no:'',
        name:'',
        username:'',
        telphone:'',
        email:'',
        status:'',
        organization:'',
        director:'',
        position:'',
        account:'',
        role_id:'',
        token: localStorage.getItem('logintoken')
      },
      //"高级搜索"参数
      searchForm: {
        id:'',
        no:'',
        username:'',
        name:'',
        telphone:'',
        email:'',
        account:'',
        organization:'',
        director:'',
        position:'',
        status: '',
        role_id:'',
      },
      // 部门参数
      unitparm: {
        userIds: '',
        deptId: '',
        deptName: ''
      },
      // 选择数据
      selectdata: [],
      // rules表单验证
      rules: {
        no: [
          { required: true, message: '请输入工号', trigger: 'change' },
          { validator: checkNo, trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'change' },
          { validator: checkUsername, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'change' }
        ],
        role_id: [{ required: true, message: '请选择角色', trigger: 'change' }],
        telphone: [
          { required: true, message: '请输入手机号', trigger: 'change' },
          {
            pattern: /^1(3\d|47|5((?!4)\d)|7(0|1|[6-8])|8\d)\d{8,8}$/,
            required: true,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            required: true,
            message: '请输入正确的邮箱',
            trigger: 'change'
          }
        ],
        account: [
          { required: true, message: '请输入系统账户', trigger: 'change' }
        ],
        organization: [
          { required: true, message: '请输入组织', trigger: 'change' }
        ],
        director: [
          { required: true, message: '请输入责任人', trigger: 'change' }
        ],
        position: [
          { required: true, message: '请输入岗位', trigger: 'change' }
        ],
      },
      //用户数据
      userData: [],
      // 数据权限
      UserDept: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 选中
      checkmenu: [],
      //参数role
      saveroleId: '',
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      //组织数据
      organizationData:[],
      //控制增加和修改页面“编码”禁用功能
      isdisabled:'',
      //组织分页数据
      orgPageData:{
        currentPage: 1,
        pageSize: 10,
        total: 20
      },
      orgs:[],
      roleIds:[],
      currentUserid:'',
    }
  },
  // 注册组件
  components: {
    Pagination,
    StatusSwitch,
  },

  watch: {},

  created() {
    this.getUserData()
  },
  methods: {
    //获取岗位数据
    getPositionData(){
      this.$axios.get('/api/position/all').then(res => {
        console.log(res);
        if(res.data.code == 200){
          this.positionData = res.data.data
      }
      }).catch();
    },
    //获取组织类别数据
    getOrganizationTypeData(){
      this.$axios.get('/api/organization/type').then(res => {
        console.log(res);
        if(res.data.code == 200){
          this.organizationTypeData = res.data.data
      }
      }).catch();
    },
    // 获取用户数据
    getUserData() {
      this.loading = false
      this.$axios.get('/api/user/'+this.pageparm.currentPage+'/'+this.pageparm.pageSize).then(res => {
        console.log(res);
        if(res.data.code == 200){
          this.userData = res.data.data.list
          this.pageparm.total = res.data.data.total
        }
      }).catch();
    },
    // 分页插件事件
    callFather(parm) {
      this.pageparm.currentPage = parm.currentPage
      this.pageparm.pageSize = parm.pageSize
      this.getdata()
    },
    // 搜索事件
    search() {
      this.$axios.post('/api/user/serch',this.searchForm).then(res => {
        console.log(res);
        if(res.data.code == 200){
          this.userData = res.data.data
        }
        this.pageparm.total = res.data.data.length
        this.closeDialog('高级搜索');
      }).catch(()=>{});
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.getOrganizationTypeData();
      this.getPositionData();
      this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.isdisabled = true
        this.title = '修改用户'
        this.editForm.no = row.no
        this.editForm.name = row.name
        this.editForm.username = row.username
        this.editForm.telphone = row.telphone
        this.editForm.email = row.email
        this.editForm.status = row.status
        this.editForm.organization = row.organization
        this.editForm.director = row.director
        this.editForm.position = row.position
        this.editForm.account = row.account
        this.editForm.role_id = row.role_id
      } else {
        this.isdisabled = false
        this.title = '添加用户'
        this.editForm.no = ''
        this.editForm.name = ''
        this.editForm.username = ''
        this.editForm.telphone = ''
        this.editForm.email = ''
        this.editForm.status = ''
        this.editForm.organization = ''
        this.editForm.director = ''
        this.editForm.position = ''
        this.editForm.account = ''
        this.editForm.role_id = ''
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editForm) {
      this.$refs[editForm].validate(valid => {
        if (!valid) {
          this.$message.error("请正确填写表单！");
        }else{
          if(this.title=='添加用户'){
            this.$axios.post('/api/user/add',this.editForm).then(res => {
              console.log(res);
              if(res.data.code == 200){
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
              }
              this.getUserData();
              this.editFormVisible = false
            }).catch((err) => {
              this.$message.error(err.response.data.message);
            });
          }else{
            this.$axios.put('/api/user/update',this.editForm).then(res => {
              console.log(res);
              if(res.data.code == 200){
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
              }
              this.getUserData();
              this.editFormVisible = false
            }).catch();
          }
        }
      })
    },
    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == 'edit') {
        this.editFormVisible = false
      } else if (dialog == 'perm') {
        this.dataAccessshow = false
      } else if (dialog == 'unit') {
        this.unitAccessshow = false
      } else if (dialog == '高级搜索'){
        this.searchVisible = false
      } else if (dialog == '角色配置'){
        this.rolesVisible = false
      }
    },
    // 删除用户
    deleteUser(index, row) {
      console.log(row);
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(row.id);
          this.$axios.delete('/api/user/delete/'+row.id).then(res => {
            console.log(res);
            if(res.data.code == 200){
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.getUserData();
            }
          }).cathch(()=>{});
        })
      .catch(()=>{})
    },
    //编辑/新增页面开关组件子传父
    changeSwitch(e){
        console.log("父组件接收到的值：",e);
        this.editForm.status = e
    },
    //搜索页面开关组件子传父
    changeSwitch_search(e){
        console.log("父组件接收到的值：",e);
        this.searchForm.status = e
    },
    //控制"选择所属组织"框
    showOrganization(){
      this.organizationFormVisible = true
      this.$axios.get('/api/organization/'+this.pageparm.currentPage+'/'+this.pageparm.pageSize).then(res => {
      console.log(res);
      if(res.data.code == 200){
        this.organizationData = res.data.data.list
        this.loading = false
        this.total = res.data.data.total
      }
      }).catch();
    },
    //"选择所属组织"选中事件
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    //"选择所属组织"保存方法
    submitOrganization(){
      this.editForm.organization = this.currentRow.org_name
      this.editForm.director = this.currentRow.director
      this.organizationFormVisible = false
    },
    //"选择所属组织"取消方法
    closeOrganization(){
      this.organizationFormVisible = false
    },
    pageSizeChange(val_pageSize) {
      console.log(`每页条数`,val_pageSize);
      this.orgPageData.pageSize = val_pageSize
      this.$axios.get('/api/organization/'+this.orgPageData.currentPage+'/'+val_pageSize).then(res => {
      console.log(res);
      if(res.data.code == 200){
        this.organizationData = res.data.data.list
        // 分页赋值
        this.orgPageData.total = res.data.data.total
      }
      }).catch();
    },
    pageCurrentChange(val_currentPage) {
      console.log(`当前页:`,val_currentPage);
      this.orgPageData.currentPage = val_currentPage
      this.$axios.get('/api/organization/'+val_currentPage+'/'+this.orgPageData.pageSize).then(res => {
      console.log(res);
      if(res.data.code == 200){
        this.organizationData = res.data.data.list
        // 分页赋值
        this.orgPageData.total = res.data.data.total
      }
      }).catch();
    },
    //高级搜索事件
    searchPlus(){
      //显示高级搜索框
      this.searchVisible = true;
      this.searchForm.status = false
      //获取组织数据
      this.getOrganizationData();
      //获取岗位数据
      this.getPositionData();
      this.resetCondition();
    },
    //获取组织数据
    getOrganizationData(){
      this.$axios.get('/api/organization/all').then((res)=>{
        console.log(res);
        if(res.data.code == 200){
          this.orgs = res.data.data
        }
      }).catch(()=>{});
    },
    resetCondition(){
      this.searchForm.no = ''
      this.searchForm.name = ''
      this.searchForm.username = ''
      this.searchForm.telphone = ''
      this.searchForm.email = ''
      this.searchForm.status = false
      this.searchForm.organization = ''
      this.searchForm.director = ''
      this.searchForm.position = ''
      this.searchForm.account = ''
    },
    //批量删除
    batchDelete(){
      console.log(this.multipleSelection);
      if(this.multipleSelection.length==0){
            this.$message({
                type: "info",
                message: "请勾选需要删除的列",
            });
            return;
        }
        this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        })
        .then(() => {
            this.$axios.put("/api/user/batchDelete",this.multipleSelection)
            .then((res) => {
              this.$refs.multipleSelectable.clearSelection();
              if (res.data.code == 200) {
                this.$message({
                  type: "success",
                  message: "已删除!",
                });
                this.getUserData();
              } else {
                this.$message({
                  type: "info",
                  message: res.data.message,
                });
              }
            })
            .catch((err) => {
              this.$message.error("删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //获取被勾选的组织的id
    handleSelectionChange(organizations) {
      for(let index in organizations){
        this.multipleSelection[index] = organizations[index].id;
      }
      console.log(this.multipleSelection);
    },
    getRowKeys(row) {
      return row.id;
    },
    //获取点击节点数据
    getNodeData(value){
      console.log(value);
      this.tableData= value
      this.pageparm.currentPage = 1
      this.pageparm.pageSize = 1
      this.pageparm.total = 1
    },
    resetPage(){
      this.pageparm.currentPage = 1
      this.pageparm.pageSize = 10
      this.getUserData();
    },

    rolesChanges(index, row){
      this.rolesVisible = true;
      this.currentUserid = row.id;
      this.getRolesData();
      this.getRolesIds(row);
    },
    //获取角色数据
    getRolesData(){
      this.$axios.get('/api/role/all').then(res=>{
        console.log(res);
        if(res.data.code==200){
            this.rolesData = res.data.data
        }
      }).catch();
    },
    //给当前用户的roles赋初值
    getRolesIds(row){
      this.$axios.get('/api/role/roles/'+row.id).then(res=>{
        console.log(res);
        if(res.data.code ==200){
          this.roleIds = res.data.data
          this.$refs.tree.setCheckedKeys(this.roleIds);
        }else{
          this.$refs.tree.setCheckedKeys([]);
        }
      }).catch(err => {});
    },
    //保存修改
    saveRoles(){
      let roles = this.$refs.tree.getCheckedKeys().toString();
      console.log("当前用户id:",this.currentUserid);
      console.log('当前用户角色:',roles);
      if(roles == ''){
        console.log("当前用户角色为空");
        this.$message.error("请选择角色！");
      }else{
        this.$axios.put('/api/role/roles/'+this.currentUserid+'/'+roles).then(res => {
          console.log(res);
          if(res.data.code == 200){
            this.$message({
              type: "success",
              message: "修改角色成功",
            });
          }
          this.rolesVisible = false;
        }).catch(err => {
          this.$message.error("请选择角色！");
        });
      }
      this.getUserData();
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 